package util;

import io.jsonwebtoken.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;

/**
 * Created by WF on 2020/4/3 15:53
 */
@ConfigurationProperties("jwt.config")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JwtUtil {
    private String key;
    private long ttl;
    //1.创建jwt
    public String createJWT(String id, String subject, String roles) {
        //1.1)定义jwtBuilder对象
        JwtBuilder jwtBuilder =
                Jwts.builder().setId(id)
                .setIssuedAt(new Date())
                .setSubject(subject)
                .claim("roles", roles)
                .signWith(SignatureAlgorithm.HS256, key);
        //1.2)如果ttl有值，代表设置了过期时间
        if(ttl > 0){
            jwtBuilder.setExpiration(new Date(System.currentTimeMillis() + ttl));
        }
        //1.3)返回生成的token
        return jwtBuilder.compact();
    }
    //2.解析token
    public Claims parseJWT(String tokenStr) {
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(tokenStr).getBody();
    }
}
